package com.kotlin.book.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.databinding.ItemHomeWeekTypeBinding
import com.kotlin.book.entry.Type

class HomeItemWeekTypeAdapter(
    private var itemList: List<Type>,
    private val callback: (Int) -> Unit
) :
    RecyclerView.Adapter<HomeItemWeekTypeAdapter.ItemViewHolder>() {
    private var currentIndex = 0

    class ItemViewHolder(itemBinding: ItemHomeWeekTypeBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {
        val text: TextView = itemBinding.text
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): HomeItemWeekTypeAdapter.ItemViewHolder {
        val binding =
            ItemHomeWeekTypeBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: HomeItemWeekTypeAdapter.ItemViewHolder, position: Int) {
        val item = itemList[position]
        holder.text.text = item.name

        if (currentIndex == position) {
            holder.text.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.white
                )
            )
            holder.text.background =
                ContextCompat.getDrawable(holder.itemView.context, R.drawable.btn_bg_small)
        } else {
            holder.text.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.text_color_hint
                )
            )
            holder.text.background = null
        }

        holder.itemView.setOnClickListener {
            callback(item.id)
            currentIndex = holder.adapterPosition
            notifyDataSetChanged()
        }
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    fun setData(newList:List<Type>){
        itemList = newList
        notifyDataSetChanged()
    }
}